package nix.hibernate;

import java.util.Arrays;
import java.util.List;

import nix.utils.HibernateUtils;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

public class DemoSQL {

	@Test
	public void fun1() {
		Session session = HibernateUtils.getCurrentSession();
		Transaction ts = session.beginTransaction();

		String sql = "select * from t_user";
		SQLQuery query = session.createSQLQuery(sql);
		// 查询默认返回Object数组的集合
		List<Object[]> list = query.list();
		for (Object[] objects : list) {
			System.out.print(Arrays.toString(objects));
			// [1, zhangSan, 123][3, lisi, 123]
		}
		// 设置实体类型，直接实现Mapping
		query.addEntity(User.class);
		List<User> userList = query.list();
		System.out.println(userList);
		ts.commit();
	}
	
	@Test
	public void fun2() {
		Session session = HibernateUtils.getCurrentSession();
		Transaction ts = session.beginTransaction();

		String sql = "select * from t_user where id = :cust_id";
		SQLQuery query = session.createSQLQuery(sql);
		// query.setParameter(0, 1);
		query.setParameter("cust_id", 1);
		query.addEntity(User.class);
		User u = (User) query.uniqueResult();
		System.out.println(u);
		ts.commit();
	}
}
